package com.voxel.sense.infomsg.module.task.list;

import android.text.TextUtils;

import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.base.RecyclerViewPresenter;
import com.voxel.sense.infomsg.module.task.overdue.OverdueTaskListActivity;
import com.voxel.sense.infomsg.module.taskfrag.TaskListFragment;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.EventBusConstants;
import cyy.example.com.facotry.model.EventEntity;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.model.api.response.TaskInfoEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.TaskNetHelper;
import cyy.example.com.facotry.share.SPEngine;

/**
 * @author ChenYiYao
 * @date 2018/12/13
 * des : agrument
 */
public class TaskListPresenter extends RecyclerViewPresenter<TaskListContract.View>
        implements TaskListContract.Presenter, DataSource.Callback<BaseEntity> {


    private String mTaskId;
    private String mDeleteTaskId;

    public TaskListPresenter(TaskListContract.View view) {
        super(view);
    }


    @Override
    public void start() {
        super.start();
        EventBus.getDefault().register(this);
    }

    @Override
    public void destroy() {
        super.destroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void loadData() {
        if (mView instanceof TaskListFragment) {
            TaskNetHelper.getTaskList(getPageDataSize() + "", getPAGE_NUMB() + "", this);
        } else if (mView instanceof OverdueTaskListActivity) {
            TaskNetHelper.getOverdueTask(getPageDataSize() + "", getPAGE_NUMB() + "", this);
        }

    }

    @Override
    protected void loadMoreData() {
        if (mView instanceof TaskListFragment) {
            TaskNetHelper.getTaskList(getPageDataSize() + "", getPAGE_NUMB() + "", this);
        } else if (mView instanceof OverdueTaskListActivity) {
            TaskNetHelper.getOverdueTask(getPageDataSize() + "", getPAGE_NUMB() + "", this);
        }
    }

    @Override
    public void doTakeTask(String TaskId, String TaskNumb) {
        mTaskId = TaskId;
        if (NetworkUtils.isConnected()) {
//            mView.showLoading("", false);
            TaskNetHelper.doTakeTask(TaskNumb, TaskId, this);
        } else {
            //网络不可用
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
            mView.onRefreshTaskStatu(Constants.TASK_UNACCEPT_TYPE, TaskId);
        }
    }

    @Override
    public void doLoadData() {
        startRefreshData();
    }

    @Override
    public void doLoadMoreData() {
        startLoadMoreData();

    }

    @Override
    public void doDeleteTask(String taskNumber, String taskId, String taskType, String taskObjects, String taskFromStatus) {
        if (!NetworkUtils.isConnected()) {
            //无网络
            mView.showError(Factory.app().getResources().getString(R.string.network_unavailable));
        } else if (!TextUtils.isEmpty(taskNumber) && !TextUtils.isEmpty(taskId) && !TextUtils.isEmpty(taskType) &&
                !TextUtils.isEmpty(taskObjects) && !TextUtils.isEmpty(taskFromStatus)) {
            mView.showLoading("");
            this.mDeleteTaskId = taskId;
            TaskNetHelper.getDeleteTask(taskNumber, taskId, taskType, taskObjects, taskFromStatus, this);
        }
    }

    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null) {
            return;
        }

        if (RequestIdFactory.GET_TASK_LIST == reqId || RequestIdFactory.GET_OVERDUE_TASK == reqId) {
            loadFinish(data);
        } else if (RequestIdFactory.ACCEPT_TASK == reqId) {
            takeTaskFinish(data);
        } else if (RequestIdFactory.DELELTE_TASK == reqId) {

            deleteTaskFinish(data);
        }
    }

    private void deleteTaskFinish(BaseEntity data) {
        mView.dimissLoading();
        if (data.isSuccess()) {
            List<TaskInfoEntity.ObBean> items = mView.getRecyclerViewAdapter().getItems();
            for (int i = items.size() - 1; i > 0; i--) {
                TaskInfoEntity.ObBean obBean = items.get(i);
                if (obBean.getTaskId().equals(mDeleteTaskId)) {
                    items.remove(i);
                    mView.getRecyclerViewAdapter().notifyDataSetChanged();
                    return;
                }
            }
        } else {
            mView.showError("删除失败");
        }
    }

    private void takeTaskFinish(BaseEntity data) {
        mView.dimissLoading();
        if (data.isSuccess()) {
            mView.onRefreshTaskStatu(Constants.TASK_ACTION_TYPE, mTaskId);
        } else {
            mView.onRefreshTaskStatu(Constants.TASK_UNACCEPT_TYPE, mTaskId);
        }
    }

    private void loadFinish(BaseEntity data) {
        if (data.isSuccess() && data.getData() != null) {
            TaskInfoEntity taskEntity = (TaskInfoEntity) data.getData();
            List<TaskInfoEntity.ObBean> ob = taskEntity.getOb();

            //将任务类型id转换为文字
            SearchMenuEntity taskType = QueryConfigManager.getInstance().getTaskType();
            if (ob != null && ob.size() > 0 && taskType != null && taskType.getStaticSystemConstantDetails() != null &&
                    taskType.getStaticSystemConstantDetails().size() > 0) {
                for (TaskInfoEntity.ObBean bean : ob) {
                    for (SearchMenuEntity.StaticSystemConstantDetailsBean typeBean : taskType.getStaticSystemConstantDetails()) {
                        if (typeBean != null && typeBean.getConstantCode().equals(bean.getTaskType())) {
                            bean.setTaskTypeDesc(typeBean.getConstantName());
                        }
                    }
                }
            }
            loadDataComplete(ob);
        } else {
            loadDataComplete(null);
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }

        if (RequestIdFactory.GET_TASK_LIST == reqId || RequestIdFactory.GET_OVERDUE_TASK == reqId) {
            loadDataComplete(null);
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.load_data_failed));
        } else if (RequestIdFactory.ACCEPT_TASK == reqId) {

            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.accept_task_failure));
            mView.onRefreshTaskStatu(Constants.TASK_UNACCEPT_TYPE, mTaskId);
            mView.dimissLoading();
        } else if (RequestIdFactory.DELELTE_TASK == reqId) {
            mView.dimissLoading();
            mView.showError("删除失败");
        }
    }

    @Subscribe
    public void EventButThread(EventEntity entity) {
        if (EventBusConstants.CHECK_TASK_PASS.equals(entity.key)) {
            //审核通过通知
            String taskNumb = (String) entity.value;
            changeTaskStatus(taskNumb, Constants.TASK_CHECK_PASS);
        } else if (EventBusConstants.CHECK_TASK_NO_PASS.equals(entity.key)) {
            String taskNumb = (String) entity.value;
            //收到驳回的通知
            changeTaskStatus(taskNumb, Constants.TASK_TASK_REJECT);
        } else if (EventBusConstants.TASK_ACTION_FINISH.equals(entity.key)) {
            //收到提交审核的通知
            String taskNumb = (String) entity.value;
            changeTaskStatus(taskNumb, Constants.TASK_FINISH_TYPE);
        }
    }

    private void changeTaskStatus(String taskNumb, String status) {
        if (mView == null || TextUtils.isEmpty(taskNumb)) {
            return;
        }
        RecyclerAdapter adapter = mView.getRecyclerViewAdapter();
        List<TaskInfoEntity.ObBean> items = adapter.getItems();
        if (!ListUtil.isEmpty(items)) {
            for (int i = items.size() - 1; i >= 0; i--) {
                TaskInfoEntity.ObBean bean = items.get(i);
                if (taskNumb.equals(bean.getTaskNumber())) {
                    if (Constants.TASK_CHECK_PASS.equals(status) || Constants.TASK_TASK_REJECT.equals(status)) {
                        //若是审核通过了，则表明任务已完结
                        items.remove(i);
                        adapter.notifyDataSetChanged();
                    } else if (Constants.TASK_FINISH_TYPE.equals(status) &&
                            !bean.getFromId().equals(SPEngine.getSPEngine().getUserInfo().getUser_id())) {
                        //待审核状态，若不是审核人，则清除任务
                        items.remove(i);
                        adapter.notifyDataSetChanged();
                    } else {
                        bean.setTaskStatu(status);
                        adapter.notifyItemChanged(i);
                    }
                    break;
                }
            }
        }
    }

}
